#include "consumptiondao.h"
#include <QDebug>

ConsumptionDAO::ConsumptionDAO(Database *db)
    : m_db(db)
{
}

QVector<QMap<QString, QVariant>> ConsumptionDAO::getConsumptionByMemberId(int memberId)
{
    QVector<QMap<QString, QVariant>> results;
    
    if (!m_db || !m_db->isConnected()) {
        qDebug() << "数据库连接无效";
        return results;
    }

    QString sql = buildBaseConsumptionQuery() + " WHERE om.customer_id = ? ORDER BY om.order_time DESC";
    
    QVector<QVariant> params;
    params.append(memberId);
    
    auto queryResults = m_db->query(sql, params);
    
    for (auto &record : queryResults) {
        processConsumptionRecord(record);
        results.append(record);
    }
    
    return results;
}

QVector<QMap<QString, QVariant>> ConsumptionDAO::getConsumptionByMemberLevel(int levelId)
{
    QVector<QMap<QString, QVariant>> results;
    
    if (!m_db || !m_db->isConnected()) {
        qDebug() << "数据库连接无效";
        return results;
    }

    QString sql = buildBaseConsumptionQuery() + " WHERE c.level_id = ? ORDER BY om.order_time DESC";
    
    QVector<QVariant> params;
    params.append(levelId);
    
    auto queryResults = m_db->query(sql, params);
    
    for (auto &record : queryResults) {
        processConsumptionRecord(record);
        results.append(record);
    }
    
    return results;
}

QVector<QMap<QString, QVariant>> ConsumptionDAO::getAllConsumptionRecords()
{
    QVector<QMap<QString, QVariant>> results;
    
    if (!m_db || !m_db->isConnected()) {
        qDebug() << "数据库连接无效";
        return results;
    }

    QString sql = buildBaseConsumptionQuery() + " ORDER BY om.order_time DESC LIMIT 1000";
    
    auto queryResults = m_db->query(sql);
    
    for (auto &record : queryResults) {
        processConsumptionRecord(record);
        results.append(record);
    }
    
    return results;
}

QVector<QMap<QString, QVariant>> ConsumptionDAO::getConsumptionByDateRange(const QDateTime &startDate, const QDateTime &endDate)
{
    QVector<QMap<QString, QVariant>> results;
    
    if (!m_db || !m_db->isConnected()) {
        qDebug() << "数据库连接无效";
        return results;
    }

    QString sql = buildBaseConsumptionQuery() + " WHERE om.order_time BETWEEN ? AND ? ORDER BY om.order_time DESC";
    
    QVector<QVariant> params;
    params.append(startDate);
    params.append(endDate);
    
    auto queryResults = m_db->query(sql, params);
    
    for (auto &record : queryResults) {
        processConsumptionRecord(record);
        results.append(record);
    }
    
    return results;
}

QVector<QMap<QString, QVariant>> ConsumptionDAO::getConsumptionByMemberAndDate(int memberId, const QDateTime &startDate, const QDateTime &endDate)
{
    QVector<QMap<QString, QVariant>> results;
    
    if (!m_db || !m_db->isConnected()) {
        qDebug() << "数据库连接无效";
        return results;
    }

    QString sql = buildBaseConsumptionQuery() + " WHERE om.customer_id = ? AND om.order_time BETWEEN ? AND ? ORDER BY om.order_time DESC";
    
    QVector<QVariant> params;
    params.append(memberId);
    params.append(startDate);
    params.append(endDate);
    
    auto queryResults = m_db->query(sql, params);
    
    for (auto &record : queryResults) {
        processConsumptionRecord(record);
        results.append(record);
    }
    
    return results;
}

QMap<QString, QVariant> ConsumptionDAO::getMemberConsumptionStats(int memberId)
{
    QMap<QString, QVariant> stats;
    
    if (!m_db || !m_db->isConnected()) {
        qDebug() << "数据库连接无效";
        return stats;
    }

    QString sql = "SELECT "
                  "COUNT(*) as order_count, "
                  "SUM(total_amount) as total_consumption, "
                  "SUM(discount_amount) as total_discount, "
                  "SUM(final_amount) as total_payment, "
                  "AVG(final_amount) as avg_order_amount, "
                  "MAX(order_time) as last_order_time "
                  "FROM order_main "
                  "WHERE customer_id = ? AND order_status = 1";
    
    QVector<QVariant> params;
    params.append(memberId);
    
    auto queryResults = m_db->query(sql, params);
    
    if (!queryResults.isEmpty()) {
        const auto &record = queryResults.first();
        stats["order_count"] = record["order_count"];
        stats["total_consumption"] = record["total_consumption"];
        stats["total_discount"] = record["total_discount"];
        stats["total_payment"] = record["total_payment"];
        stats["avg_order_amount"] = record["avg_order_amount"];
        stats["last_order_time"] = record["last_order_time"];
    }
    
    return stats;
}

QVector<QMap<QString, QVariant>> ConsumptionDAO::getConsumptionStatsByLevel()
{
    QVector<QMap<QString, QVariant>> results;
    
    if (!m_db || !m_db->isConnected()) {
        qDebug() << "数据库连接无效";
        return results;
    }

    QString sql = "SELECT "
                  "ml.level_id, "
                  "ml.level_name, "
                  "COUNT(om.order_id) as order_count, "
                  "COUNT(DISTINCT om.customer_id) as member_count, "
                  "SUM(om.total_amount) as total_consumption, "
                  "SUM(om.discount_amount) as total_discount, "
                  "SUM(om.final_amount) as total_payment, "
                  "AVG(om.final_amount) as avg_order_amount "
                  "FROM membership_level ml "
                  "LEFT JOIN customer c ON ml.level_id = c.level_id "
                  "LEFT JOIN order_main om ON c.customer_id = om.customer_id AND om.order_status = 1 "
                  "GROUP BY ml.level_id, ml.level_name "
                  "ORDER BY ml.level_id";
    
    auto queryResults = m_db->query(sql);
    
    for (const auto &record : queryResults) {
        results.append(record);
    }
    
    return results;
}

QVector<QMap<QString, QVariant>> ConsumptionDAO::getConsumptionDetails(int orderId)
{
    QVector<QMap<QString, QVariant>> results;
    
    if (!m_db || !m_db->isConnected()) {
        qDebug() << "数据库连接无效";
        return results;
    }

    QString sql = "SELECT "
                  "od.order_id, "
                  "od.product_id, "
                  "p.product_name, "
                  "p.specification, "
                  "od.quantity, "
                  "od.unit_price, "
                  "od.subtotal, "
                  "od.is_discounted "
                  "FROM order_detail od "
                  "JOIN product p ON od.product_id = p.product_id "
                  "WHERE od.order_id = ? "
                  "ORDER BY od.product_id";
    
    QVector<QVariant> params;
    params.append(orderId);
    
    auto queryResults = m_db->query(sql, params);
    
    for (const auto &record : queryResults) {
        results.append(record);
    }
    
    return results;
}

QString ConsumptionDAO::buildBaseConsumptionQuery() const
{
    return "SELECT "
           "om.order_id, "
           "om.order_time, "
           "om.customer_id, "
           "COALESCE(c.customer_id, 0) as member_id, "
           "COALESCE(c.name, '非会员') as customer_name, "
           "COALESCE(c.phone, '') as customer_phone, "
           "COALESCE(c.level_id, 0) as level_id, "
           "COALESCE(ml.level_name, '非会员') as level_name, "
           "om.total_amount, "
           "om.discount_amount, "
           "om.final_amount, "
           "pm.method_name, "
           "om.order_status "
           "FROM order_main om "
           "LEFT JOIN customer c ON om.customer_id = c.customer_id "
           "LEFT JOIN membership_level ml ON c.level_id = ml.level_id "
           "LEFT JOIN payment_method pm ON om.method_id = pm.method_id";
}

void ConsumptionDAO::processConsumptionRecord(QMap<QString, QVariant> &record) const
{
    // 计算节省金额百分比
    double totalAmount = record["total_amount"].toDouble();
    double discountAmount = record["discount_amount"].toDouble();
    
    if (totalAmount > 0) {
        double discountRate = (discountAmount / totalAmount) * 100;
        record["discount_rate"] = QString::number(discountRate, 'f', 1) + "%";
    } else {
        record["discount_rate"] = "0.0%";
    }
    
    // 格式化订单状态
    int status = record["order_status"].toInt();
    QString statusText;
    switch (status) {
        case 0: statusText = "待支付"; break;
        case 1: statusText = "已支付"; break;
        case 2: statusText = "已完成"; break;
        case 3: statusText = "已取消"; break;
        case 4: statusText = "已退款"; break;
        default: statusText = "未知状态"; break;
    }
    record["status_text"] = statusText;
    
    // 格式化时间显示
    QDateTime orderTime = record["order_time"].toDateTime();
    record["formatted_time"] = orderTime.toString("yyyy-MM-dd hh:mm:ss");
    record["date_only"] = orderTime.toString("yyyy-MM-dd");
}